package com.download.download;

import java.io.IOException;
import java.io.RandomAccessFile;

import com.download.exception.DownloadException;

public class FileBlock {
    
	//随机访问文件
    private RandomAccessFile fileBlock;
	
	/**
	 * 构造时指定写入点。
	 * @param fileName 文件绝对路径含文件名
	 * @param pos 写入点位置
	 * @throws IOException 
	 */
    public FileBlock(String fileName, long startpostion) throws IOException {
        fileBlock = new RandomAccessFile(fileName,"rw");
        fileBlock.seek(startpostion);
    }

    /**
	 * 将缓冲区内容写入随机文件
	 * @param buffer 缓冲区
	 * @param startPosition 写入点
	 * @param length 写入长度
	 * @return 已经写入的字节数
	 */
	public int write(byte[] buffer,int startPosition,int length) {
	    int i = -1;
	    try {
	        fileBlock.write(buffer, startPosition, length);
	        i = length;
	    } catch (IOException e) {
	        throw new DownloadException("FileBlock.write()", e);
	    }
	    return i;
	}

	public void close() throws IOException {
	    fileBlock.close();
	}

}
